<template>
  <!-- 排序弹窗 -->
  <el-dialog v-model="isShow" width="800" title="排序">
    <div>
      <div>
        <el-button type="primary" icon="Top" @click="topHandle">上移</el-button>
        <el-button type="primary" icon="Bottom" @click="bottomHandle">下移</el-button>
        <el-button type="primary" icon="SortUp" @click="toUp">移至最上</el-button>
        <el-button type="primary" icon="SortDown" @click="toDown">移至最下</el-button>
      </div>
      <div class="ptb10">
        <el-radio-group v-model="radio">
          <el-radio :label="index" v-for="(item, index) in bufferData">{{ item.name }}</el-radio>
        </el-radio-group>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShow = false">取消</el-button>
        <el-button type="primary" @click="confirmSort">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
export default {
  props: {
    data: Array,
  },
  watch: {
    data: {
      handler() {
        this.bufferData = JSON.parse(JSON.stringify(this.data));
      },
      deep: true,
    },
  },
  data() {
    return {
      isShow: false,
      radio: 0,
      bufferData: [],
    };
  },
  methods: {
    open() {
      this.isShow = true;
    },
    confirmSort() {
      this.bufferData = this.bufferData.map((item, index) => {
        return {
          ...item,
          sort: index + 1,
        };
      });
      this.isShow = false;
      this.$emit('sort', this.bufferData);
    },
    topHandle() {
      if (this.radio == 0) {
        this.$message.warning('已经是最上了');
        return;
      }
      const prev = this.bufferData[this.radio - 1];
      const current = this.bufferData[this.radio];
      this.bufferData.splice(this.radio - 1, 2, current, prev);
      this.radio--;
    },
    bottomHandle() {
      if (this.radio == this.bufferData.length - 1) {
        this.$message.warning('已经是最下了');
        return;
      }
      const next = this.bufferData[this.radio + 1];
      const current = this.bufferData[this.radio];
      this.bufferData.splice(this.radio, 2, next, current);
      this.radio++;
    },
    toUp() {
      const current = this.bufferData.splice(this.radio, 1)[0];
      this.bufferData.unshift(current);
      this.radio = 0;
    },
    toDown() {
      const current = this.bufferData.splice(this.radio, 1)[0];
      this.bufferData.push(current);
      this.radio = this.bufferData.length - 1;
    },
  },
};
</script>

<style scoped>
.el-radio-group,
.el-radio {
  display: block !important;
}
</style>
